package com.zhidao.backend.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhidao.backend.common.FollowRequest;
import com.zhidao.backend.common.StatusCode;
import com.zhidao.backend.entity.Follow;
import com.zhidao.backend.exception.BusinessException;
import com.zhidao.backend.mapper.FollowMapper;
import com.zhidao.backend.service.IFollowService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 关注服务实现
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Override
    public void follow(@NotNull FollowRequest followRequest) {
        Long bloggerId = followRequest.getBloggerId();
        Long followerId = followRequest.getFollowerId();
        Follow follow = new Follow();
        follow.setBloggerId(bloggerId);
        follow.setFollowerId(followerId);
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        follow.setFollowTime(timestamp);
        follow.setDeleted(false);
        int res = baseMapper.insert(follow);
        if (res < 1) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "关注失败，请重试");
        }
    }

    @Override
    public List<Long> getSubscribeList(Long id) {
        List<Follow> subscribeList =  baseMapper.selectList(new QueryWrapper<Follow>().eq("follower_id", id));
        if (subscribeList == null) {
            return null;
        }
        List<Long> subscribeIdList = new ArrayList<>();
        for (Follow follow : subscribeList) {
            subscribeIdList.add(follow.getBloggerId());
        }
        return subscribeIdList;
    }

    @Override
    public void unfollow(FollowRequest followRequest) {
        Long bloggerId = followRequest.getBloggerId();
        Long followerId = followRequest.getFollowerId();
        int res = baseMapper.delete(new QueryWrapper<Follow>().eq("blogger_id", bloggerId).eq("follower_id", followerId));
        System.out.println(res);
        if (res < 1) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "取消关注失败，请重试");
        }
    }
}
